# encoding: utf-8
import pyexiv2
import fractions
 
 
#把小数转成度分秒的形式
def convToDuFenMiao(num):
    du, aft0 = int(num), num-int(num)
 
    miao = aft0 * 60 * 60
    fen = int(miao/60)
    miao = miao - fen*60
 
    return (du), (fen), (miao)
 
 
#写个方法，把小数转成分数，只有这种格式才能写到pyexiv2库里的GPS信息中
def coordinate2rational(D, M, S):
    return (fractions.Fraction(D, 1), fractions.Fraction(int((M + S / 60) * 1000000), 1000000), fractions.Fraction(0, 1))

def wGps(lng,lat,name):
    #自己定义的用于测试的经纬度
    longituade = lng
    latituade = lat
     
    #判断东西经，南北纬
    if longituade > 0:
        long_location = 'E'
    else:
        long_location = 'W'
    if latituade > 0:
        lati_location = 'N'
    else:
        lati_location = 'S'
     
    longituade = abs(longituade)
    latituade = abs(latituade)
     
    #pyexiv2库打开一个jpg文件，参数是文件路径
    template = pyexiv2.ImageMetadata('D://java_down//' + name)
    template.read()
    #添加经纬度信息
    longdu,longfen,longmiao = convToDuFenMiao(longituade)
    template["Exif.GPSInfo.GPSLongitude"] = coordinate2rational(longdu, longfen, longmiao)
    template["Exif.GPSInfo.GPSLongitudeRef"] = long_location
     
    latdu, latfen, latmiao = convToDuFenMiao(latituade)
    template["Exif.GPSInfo.GPSLatitude"] = coordinate2rational(latdu, latfen, latmiao)
    template["Exif.GPSInfo.GPSLatitudeRef"] = lati_location
     
    #保存，完成
    template.write()
    print("done" + name)

if __name__ == '__main__':
    print(convToDuFenMiao(123.123456))
